<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MArea;
use App\Models\MExpressCompany;
use App\Models\MLog;
use App\Models\MOrder;
use App\Models\MProduct;
use Illuminate\Http\Request;
use Mockery\CountValidator\Exception;
use Symfony\Component\Finder\Expression\Expression;


/**
 * 商品管理控制器
 */
class ProductController extends Controller
{
    /**
     * 添加/编辑商品页面
     */
    public function editPage($pro = 0)
    {
        $this->data['product'] = MProduct::find($pro);
        return view("admin.product_add")->with($this->data);
    }

    /**
     * 商品编辑保存
     */
    public function editSave(Request $request)
    {
        if (!$this->validateReq($request, MProduct::editRulesWithMsg(0), MProduct::editRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        $product = MProduct::find($request->id);
        if (empty($product)) {
            $product = new MProduct();
        }

        //接收商品图片
        $imgPath = null;
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $file = $request->file('file');
            $filename = md5_file($file->getPathname()) . "." . $file->getClientOriginalExtension();   //md5 + 扩展名
            $file->move('uploads/imgs/', $filename);
            $imgPath = 'uploads/imgs/' . $filename;
        }

        if ($product->addOne($request, $imgPath)) {
            $this->data = $this->makeJsCode(0, "商品添加成功！");
        } else {
            $this->data = $this->makeJsCode(1, "商品添加失败！");
        }

        return response()->json($this->data);
    }

    /**
     * 商品列表页面
     * $flag = 0 在售商品列表
     * $flag = 1 已下架商品列表
     */
    public function productsPage(Request $request, $flag, $index = 1)
    {
        $query = (new MProduct())->query();
        $this->fyInit(route('admin.product.list'), 15);
        if ($flag == 0) {
            $query = $query->where('status', MProduct::$STATUS_SALE);
        } elseif ($flag == 1) {
            $query = $query->where('status', MProduct::$STATUS_DOWN);
        }
        $this->fyCalc($query->count(), $index);
        $this->data['list'] = $query->skip($this->fy_pgOffset)->take($this->fy_pgSize)
            ->orderBy('time', 'desc')->get();
        $this->data['flag'] = $flag;
        $this->fyViewInit($this->data);
        return view('admin.products')->with($this->data);
    }

    /**
     * 上/下架商品
     * $flag = 0 上架商品
     * $flag = 1 下架商品
     * $id = 商品ID
     */
    public function proStatus($flag, $id)
    {
        $product = MProduct::find($id);
        if ($flag == MProduct::$STATUS_SALE) {
            $product->status = MProduct::$STATUS_SALE;

        } elseif ($flag == MProduct::$STATUS_DOWN) {
            $product->status = MProduct::$STATUS_DOWN;
        } else {
            $this->data = $this->makeJsCode(1, "非法的操作！");
            return back()->with($this->data);
        }

        if ($product->save()) {
            $this->data = $this->makeJsCode(0, "操作成功！");
        } else {
            $this->data = $this->makeJsCode(1, "操作失败！");
        }

        return back()->with($this->data);
    }

    /**
     * 订单列表
     */
    public function ordersPage($flag, $index = 1)
    {
        $this->fyInit(route('admin.order'), 15);
        $query = (new MOrder())->query();
        if ($flag == 0) {
            $query = $query->where('status', MOrder::$STATUS_PAY_OK);
        } elseif ($flag == 1) {
            $query = $query->where('status', MOrder::$STATUS_PAY_SEND)
                ->orWhere('status', MOrder::$STATUS_PAY_END);
        }

        $this->fyCalc($query->count(), $index);
        $orders = $query->orderBy('create_time', 'desc')->skip($this->fy_pgOffset)->take($this->fy_pgSize)->get();
        foreach ($orders as &$order) {
            $good_ids = explode(',', $order->good_id);
            $good_nos = explode(',', $order->good_no);
            $good_nums = explode(',', $order->num);

            $good_info_str = '';
            foreach ($good_ids as $k => $good_id) {
                $good = MProduct::where("id", $good_ids[$k])->where('no', $good_nos[$k])->first();
                if (!$good) {
                    throw new Exception("未查找到相关商品");
                }
                $good_name = $good->title;
                $good_link = route('admin.product', ['pro' => $good_ids[$k]]);
                $good_info_str .= "<a href='$good_link' target='_blank'>$good_name</a> * $good_nums[$k]<br>";
            }
            $order->good_info = $good_info_str;
        }
//        dd($orders);
        $this->data['orders'] = $orders;
        $this->data['flag'] = $flag;
        $this->fyViewInit($this->data);
        return view('admin.orders')->with($this->data);
    }

    public function orderEditPage($oid)
    {
        $order = MOrder::find($oid);

        $good_ids = explode(',', $order->good_id);
        $good_nos = explode(',', $order->good_no);
        $good_nums = explode(',', $order->num);

        $good_info_str = '';
        foreach ($good_ids as $k => $good_id) {
            $good = MProduct::where("id", $good_ids[$k])->where('no', $good_nos[$k])->first();
            if (!$good) {
                throw new Exception("未查找到相关商品");
            }
            $good_name = $good->title;
            $good_link = route('admin.product', ['pro' => $good_ids[$k]]);
            $good_info_str .= "<a href='$good_link' target='_blank'>$good_name</a> * $good_nums[$k]<br>";
        }
        $order->good_info = $good_info_str;

        $this->data['order'] = $order;
        $this->data['good'] = MProduct::where('no', $this->data['order']->good_no)->first();
        $this->data['express_companys'] = MExpressCompany::all();
        $this->data['provinces'] = MArea::where("parent_id", 0)->get();
        $this->data['citys'] = MArea::where("parent_id", $order->province)->get();
        $this->data['countys'] = MArea::where("parent_id", $order->city)->get();
        return view('admin.order_edit')->with($this->data);
    }

    /**
     * 修改订单状态 发货
     * $id = 发货订单ID
     */
    public function ordersShip(Request $request, $id)
    {
        //检查数据完整性
        if (!$request->has(['province', 'city', 'county', 'addr', 'tel', 'express_company_id', 'express_no'])) {
            return response()->json($this->makeJsCode(1, "请检查表单数据完整性！"));
        }
        $order = MOrder::find($id);

        if (empty($order)) { //判断订单是否存在
            return response()->json($this->makeJsCode(1, "订单不存在！"));
        }

        if ($order->status != MOrder::$STATUS_PAY_OK) { //判断订单是否已发货
            return response()->json($this->makeJsCode(1, "订单已发货或已完结不可再次修改！"));
        }

        if ($order->shipOrders($request)) {
            $this->data = $this->makeJsCode(0, '操作成功！');
            MLog::log("修改了会员 {$order->user->username}编号为 $order->no 的订单状态为发货 !",1);
        } else {
            $this->data = $this->makeJsCode(1, '操作失败！');
        }

        return response()->json($this->data);
    }

    /**
     * 删除订单
     * $id = 要删除的订单
     */
    public function ordersDel($id)
    {
        $order = Morder::find($id);
        if (empty($order)) { //判断订单是否存在
            return back()->with($this->makeJsCode(1, "订单不存在！"));
        }

        if ($order->delete()) {
            $this->data = $this->makeJsCode(0, '删除成功！');
            MLog::log("删除了会员 {$order->user->username}编号为 $order->no 的订单!",1);
        } else {
            $this->data = $this->makeJsCode(1, '删除失败！');
        }

        return back()->with($this->data);
    }

    /**
     * 完结订单
     * $id = 要完结的订单
     */
    public function ordersEnd($id)
    {
        $order = Morder::find($id);
        if (empty($order)) { //判断订单是否存在
            return back()->with($this->makeJsCode(1, "订单不存在！"));
        }

        if ($order->status != MOrder::$STATUS_PAY_SEND) { //判断订单是否已完结
            return back()->with($this->makeJsCode(1, "订单未发货或已完结不可再次修改！"));
        }

        if ($order->endOrders()) {
            $this->data = $this->makeJsCode(0, '操作成功！');
            MLog::log("修改了会员 {$order->user->username}编号为 $order->no 的订单状态为完结 !",1);
        } else {
            $this->data = $this->makeJsCode(1, '操作失败！');
        }

        return back()->with($this->data);
    }

}